const Koa = require('koa')
const app = new Koa()
const bodyParser = require('koa-bodyparser')
const logger = require('koa-logger')
const Moment = require('moment')
const KoaJwt = require('koa-jwt')
const { code } = require('./static/secret')
const lostHandler = require('./middlewares/lostHandler')
const error = require('koa-json-error')
const parameter = require('koa-parameter')
const router = require('./router')
const cors = require('@koa/cors')
const mongo = require('./mongodb')

app.use(error({ postFormat: (e, { stack, ...rest }) => process.env.NODE_ENV === 'production' ? rest : { stack, ...rest } }))
app.use(cors())
app.use(async (ctx, next) => {
  await mongo.connect()
  await next()
  await mongo.close()
})
app.use(bodyParser())
app.use(logger(str => {
  console.log(Moment().format('YYYY-MM-DD HH:mm:ss') + str)
}))
app.use(parameter(app))
app.use(lostHandler.errorHandle)
app.use(KoaJwt({ secret: code }).unless(
  { path: [/^.*\/login/, /^.*\/register/] }))

router(app)
module.exports = app
// app.listen(3000, () => { console.log('service is open') })
